package org.bw.bookstore.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bw.bookstore.book.mapper.*;
import org.bw.bookstore.book.service.OrderService;
import org.bw.bookstore.common.entity.*;
import org.bw.bookstore.common.utils.ResponseResult;
import org.bw.bookstore.common.utils.StringTools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @program:wisdom_bookstore
 * @description:订单接口实现类
 * @author:钟乐
 * @create:2020-10-22 10:53
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    /**
    　　* TODO  checkBookSingleNoPay--返回未付款书籍详情
    　　* @Param [rfids] 
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/27 10:12 
    　　*/
    @Override
    public ResponseResult checkBookSingleNoPay(String rfids) {
        ResponseResult result = ResponseResult.SUCCESS();
        Map<String, Object> resultMap = new HashMap<>();

        //判断并进行rfids拆分
        if(rfids == null || rfids.equals("")){
            return result.setFail("没有rfids");
        }
        String[] split = rfids.split(",");

        //查找所有rfid的图书详情
        List<TbBookDetailed> bookDetailedList = bookDetailedMapper.findByRFID(split);
        //查找所有的rfid的单品记录
        List<TbBookSingle> bookSingleList = bookDetailedMapper.findSingleByRFID(split);

        //循环书籍详情
        for (TbBookDetailed bookDetailed : bookDetailedList){
            List<TbBookSingle> tbBookSingleList = new ArrayList<>();
            //循环单品书籍
            for (TbBookSingle bookSingle : bookSingleList){
                //如果单品书籍和图书详情互相对应 就存到集合中
                if (bookDetailed.getCode().equals(bookSingle.getBookDetailedCode())){
                    tbBookSingleList.add(bookSingle);
                }
            }
            //添加到图书详情里
            bookDetailed.setTbBookSingleList(tbBookSingleList);
        }

        //返回结果
        resultMap.put("bookDetailedList", bookDetailedList);
        result.setResult(resultMap);
        return result;
    }

    /**
    　　* TODO  findPayRecordById--用户查看自己的支付记录
    　　* @Param [userInfoCode]
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/30 8:35
    　　*/
    @Override
    public ResponseResult findPayRecordById(String userInfoCode) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //1.判断用户是否存在
        TbUserInfo tbUserInfo = memberMapper.selectOne(
                new QueryWrapper<TbUserInfo>()
                        .eq("code",userInfoCode)
        );
        if(tbUserInfo==null){
            return result.setFail("该用户未登录");
        }

        //根据用户code查找支付记录
        List<TbPayRecord> payRecordById = payRecordMapper.findPayRecordById(userInfoCode);

        //System.out.println(payRecordById);
        //然后遍历购物车记录去查询书籍详情
        for(TbPayRecord tbPayRecord:  payRecordById){
            TbOrderRecord tbOrderRecord = orderRecordMapper.selectOne(
                    new QueryWrapper<TbOrderRecord>()
                    .eq("code",tbPayRecord.getOrderRecordCode())
            );
            tbPayRecord.setTbOrderRecord(tbOrderRecord);
            payRecordMapper.updateById(tbPayRecord);
            TbUserInfo tbUserInfo1 = memberMapper.selectOne(
                    new QueryWrapper<TbUserInfo>()
                    .eq("code",tbPayRecord.getUserInfoCode())
            );
            System.out.println(tbUserInfo1);;
            tbPayRecord.setTbUserInfo(tbUserInfo1);
            payRecordMapper.updateById(tbPayRecord);
        }

        resultMap.put("payRecordById",payRecordById);
        result.setResult(resultMap);
        return result;
    }

    /**
     　　* TODO  createOrderRecord1--用户选择书籍与数量然后生成订单记录（线上）
     　　* @Param [orderRecord, code, num]
     　　* @return com.bw.common.utils.ResponseResult
     　　* @author 钟乐
     　　* @date 2020/11/1 20:44
     　　*/
    @Override
    public ResponseResult createOrderRecord1(TbOrderRecord orderRecord, String code, Integer num) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        ArrayList<TbOrderGoods> tbOrderGoodsList = new ArrayList<>();

        //1.根据书籍code查询出书籍详情
        TbBookDetailed tbBookDetailed = bookDetailedMapper.selectOne(
                new QueryWrapper<TbBookDetailed>()
                        .eq("code", code)
        );
        System.out.println("-----"+tbBookDetailed);
        //2.得到想要购买的书籍的存货量
        Integer bookInventoryLevel = tbBookDetailed.getBookInventoryLevel();
        //3.如果想要购买的数量小于等于库存量，可以进行下一步
        if(bookInventoryLevel>=num) {
            //4、在订单商品里添加数据
            TbOrderGoods tbOrderGoods = new TbOrderGoods();
            tbOrderGoods.setCode(StringTools.getRandomString(32));
            tbOrderGoods.setGoodsName(tbBookDetailed.getBookName());
            tbOrderGoods.setGoodsPrice(tbBookDetailed.getBookPrice());
            tbOrderGoods.setGoodsTotalPrice(num * tbBookDetailed.getBookPrice());
            tbOrderGoods.setBuyNum(num);
            tbOrderGoods.setDeleted(0);
            tbOrderGoods.setCreateTime(new Date());
            tbOrderGoods.setBookDetailedCode(code);
            tbOrderGoods.setBookDetailed(tbBookDetailed);
            orderGoodsMapper.insert(tbOrderGoods);
            System.out.println("1111234567---------------------"+tbOrderGoods);
            tbOrderGoodsList.add(tbOrderGoods);

            resultMap.put("tbOrderGoodsList", tbOrderGoodsList);
            //5、把订单商品集合放进订单记录里
            //6、根据订单商品添加订单记录
            orderRecord.setTbOrderGoodsList(tbOrderGoodsList);
            orderRecord.setOrderPrice(tbOrderGoods.getGoodsTotalPrice());
            orderRecord.setCode(StringTools.getRandomString(32));
            orderRecord.setOrderStatus(0);
            orderRecord.setDeleted(0);
            orderRecord.setCreateTime(new Date());
            orderRecord.setOrderTotalPrice(tbOrderGoods.getGoodsTotalPrice());
            orderRecord.setUserInfoCode(orderRecord.getUserInfoCode());
            orderRecord.setGoodsName(tbBookDetailed.getBookName());
            orderRecord.setBuyNum(tbOrderGoods.getBuyNum());
            TbUserInfo tbUserInfo = memberMapper.selectOne(
                    new QueryWrapper<TbUserInfo>()
                            .eq("code", orderRecord.getUserInfoCode()));

            orderRecord.setTbUserInfo(tbUserInfo);

            orderRecordMapper.insert(orderRecord);
            for (TbOrderGoods tbOrderGoods1 : tbOrderGoodsList) {
                tbOrderGoods1.setOrderRecordCode(orderRecord.getCode());
                orderGoodsMapper.updateById(tbOrderGoods1);
            }
            System.out.println("---------------------"+orderRecord);
            resultMap.put("orderRecord", orderRecord);
            result.setResult(resultMap);
            return result;
        }
        return result.setFail("不好意思，该书籍存货量不足");

    }

    /**
    　　* TODO  createOrderRecord--生成订单商品+订单记录
    　　* @Param [orderRecord] 
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/24 16:03
    　　*/
    @Override
    public ResponseResult createOrderRecord(TbOrderRecord orderRecord,String rfids) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        ArrayList<TbOrderGoods> tbOrderGoodsList = new ArrayList<>();
        //1、调用根据RFID得到书籍详情的集合的方法得到未付款书籍集合
        ResponseResult responseResult = checkBookSingleNoPay(rfids);
        Map<String, Object> map = (Map<String, Object>)responseResult.getResult();
        List<TbBookDetailed> bookDetailedList = (List<TbBookDetailed>)map.get("bookDetailedList");
        //2、循环往订单商品里添加数据
        for(TbBookDetailed tbBookDetailed:bookDetailedList){
            TbOrderGoods tbOrderGoods = new TbOrderGoods();
            tbOrderGoods.setBookDetailed(tbBookDetailed);
            tbOrderGoods.setBookDetailedCode(tbBookDetailed.getCode());
            tbOrderGoods.setGoodsName(tbBookDetailed.getBookName());
            tbOrderGoods.setGoodsPrice(tbBookDetailed.getBookPrice());
            tbOrderGoods.setBuyNum(tbBookDetailed.getTbBookSingleList().size());
            tbOrderGoods.setCode(StringTools.getRandomString(32));
            tbOrderGoods.setCreateTime(new Date());
            tbOrderGoods.setDeleted(0);
            tbOrderGoods.setGoodsTotalPrice(tbBookDetailed.getBookPrice()*tbBookDetailed.getTbBookSingleList().size());
            orderGoodsMapper.insert(tbOrderGoods);
            tbOrderGoodsList.add(tbOrderGoods);

        }
        resultMap.put("tbOrderGoodsList",tbOrderGoodsList);
        //3、把订单商品集合放进订单记录里

        orderRecord.setTbOrderGoodsList(tbOrderGoodsList);
        //4、计算出订单记录的金额
        Double goodsTotalPrice = 0.0;
        for(TbOrderGoods tbOrderGoods : tbOrderGoodsList){
            goodsTotalPrice += tbOrderGoods.getGoodsPrice()*tbOrderGoods.getBuyNum();
        }
        orderRecord.setOrderTotalPrice(goodsTotalPrice);
        //3、根据订单商品添加订单记录
        orderRecord.setOrderPrice(goodsTotalPrice);
        orderRecord.setCode(StringTools.getRandomString(32));
        orderRecord.setOrderStatus(0);
        orderRecord.setDeleted(0);
        orderRecord.setCreateTime(new Date());
        orderRecord.setUserInfoCode(orderRecord.getUserInfoCode());

        TbUserInfo tbUserInfo = memberMapper.selectById(orderRecord.getUserInfoCode());
        System.err.println(tbUserInfo);
        orderRecord.setTbUserInfo(tbUserInfo);
        System.out.println(orderRecord);

        orderRecordMapper.insert(orderRecord);
        for(TbOrderGoods tbOrderGoods : tbOrderGoodsList){
            tbOrderGoods.setOrderRecordCode(orderRecord.getCode());
            orderGoodsMapper.updateById(tbOrderGoods);
        }
        System.out.println(orderRecord);
        resultMap.put("orderRecord",orderRecord);
        result.setResult(resultMap);
        return result;
    }

    /**
    　　* TODO  findOneOrderRecordOnline--用户查看自己的订单记录
    　　* @Param [userInfoCode]
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/27 10:17
    　　*/
    @Override
    public ResponseResult findOneOrderRecordOnline(String userInfoCode) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //1、根据订单id查询详细信息，包括用户信息以及书籍信息
        List<TbOrderRecord> oneOrderRecordOnline = orderRecordMapper.findOneOrderRecordOnline(userInfoCode);
        TbUserInfo tbUserInfo = memberMapper.selectById(userInfoCode);

        if(oneOrderRecordOnline==null){
            return result.setFail("您的这条订单记录不存在");
        }

        for(TbOrderRecord orderRecord:oneOrderRecordOnline){
            //将超过30分钟的订单设置取消
            if(orderRecord.getOrderStatus().equals(0)&&new Date().getTime()-orderRecord.getCreateTime().getTime()>1800000){
                orderRecord.setOrderStatus(2);
                orderRecordMapper.updateById(orderRecord);
                result.setMessage("您有订单超时未支付，已自动取消");
            }

            TbOrderGoods tbOrderGoods = orderGoodsMapper.selectOne(
                    new QueryWrapper<TbOrderGoods>()
                            .eq("order_record_code", orderRecord.getCode())
            );
            orderRecord.setBuyNum(tbOrderGoods.getBuyNum());
            orderRecord.setGoodsName(tbOrderGoods.getGoodsName());

            orderRecord.setTbUserInfo(tbUserInfo);
            orderRecordMapper.updateById(orderRecord);
        }
        //3、返回查询到的结果
        resultMap.put("oneOrderRecordOnline",oneOrderRecordOnline);
        result.setResult(resultMap);
        return result;
    }

    /**
    　　* TODO  cancelOrderRecord--取消订单
    　　* @Param [userInfoCode, orderRecordCode]
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/23 11:43
    　　*/
    @Override
    public ResponseResult cancelOrderRecord(String userInfoCode, Integer orderRecordId) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //1、判断是否有与该用户和订单code对应的记录，且记录状态为未完成
        List<TbOrderRecord> tbOrderRecords = orderRecordMapper.selectList(
                new QueryWrapper<TbOrderRecord>()
                        .eq("user_info_code", userInfoCode)
                        .eq("id", orderRecordId)
                        .eq("deleted",0)
        );
        //2、返回不存在的提示信息
        if(tbOrderRecords.size()<=0){
            return result.setFail("您的这条订单记录不存在");
        }
        //3、修改状态为已取消
        for(TbOrderRecord tbOrderRecord:tbOrderRecords){
            tbOrderRecord.setOrderStatus(2);
            orderRecordMapper.updateById(tbOrderRecord);
            resultMap.put("tbOrderRecord",tbOrderRecord);
            result.setResult(resultMap);
        }
        result.setMessage("取消订单成功");
        return result;
    }

    /**
     　　* TODO  createPayRecord--生成支付记录并将订单记录中的状态改为已完成
     　　* @Param [payRecord]
     　　* @return com.bw.common.utils.ResponseResult
     　　* @author 钟乐
     　　* @date 2020/10/25 10:01
     　　*/
    @Override
    public ResponseResult createPayRecord(TbPayRecord payRecord) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        //1、判断用户是否存在
        TbUserInfo tbUserInfo = memberMapper.selectOne(
                new QueryWrapper<TbUserInfo>()
                        .eq("code",payRecord.getUserInfoCode())
        );
        if(tbUserInfo==null){
            return result.setFail("该用户未登录");
        }

        //查询要支付的订单
        TbOrderRecord tbOrderRecord = orderRecordMapper.selectOne(
                new QueryWrapper<TbOrderRecord>()
                        .eq("user_info_code", payRecord.getUserInfoCode())
                        .eq("code",payRecord.getOrderRecordCode())
                        .eq("order_status",0)
                        .last("limit 1")
        );
        System.out.println("--------tbOrderRecord----------"+tbOrderRecord);
        if(tbOrderRecord.getOrderStatus().equals(1)||tbOrderRecord.getOrderStatus().equals(2)){
            return result.setFail("该订单已支付或已经取消");
        }

        List<TbOrderGoods> tbOrderGoods = orderGoodsMapper.selectList(
                new QueryWrapper<TbOrderGoods>()
                        .eq("order_record_code", payRecord.getOrderRecordCode())
        );
        System.out.println("------tbOrderGoods------"+tbOrderGoods);
        tbOrderRecord.setTbOrderGoodsList(tbOrderGoods);
        orderRecordMapper.updateById(tbOrderRecord);
        System.out.println(tbOrderRecord);

        List<TbOrderGoods> tbOrderGoodsList = tbOrderRecord.getTbOrderGoodsList();
        System.out.println("---------tbOrderGoodsList-----------"+tbOrderGoodsList);
        for (TbOrderGoods tbOrderGoods1 : tbOrderGoodsList) {
            String bookDetailedCode = tbOrderGoods1.getBookDetailedCode();
            System.out.println(bookDetailedCode);
            TbBookDetailed tbBookDetailed = bookDetailedMapper.selectOne(
                    new QueryWrapper<TbBookDetailed>()
                            .eq("code", bookDetailedCode)
            );
            Integer bookInventoryLevel = tbBookDetailed.getBookInventoryLevel();
            if (bookInventoryLevel < tbOrderGoods1.getBuyNum()) {
                return result.setFail("不好意思，书籍库存量不足");
            }
            //3、将前台传过来的数据添加在支付记录
            TbPayRecord tbPayRecord = new TbPayRecord();
            tbPayRecord.setCode(StringTools.getRandomString(32));
            tbPayRecord.setCreateTime(new Date());
            tbPayRecord.setPayAmount(payRecord.getPayAmount());
            tbPayRecord.setUserInfoCode(payRecord.getUserInfoCode());
            tbPayRecord.setPayStatus(payRecord.getPayStatus());
            tbPayRecord.setOrderRecordCode(payRecord.getOrderRecordCode());
            tbPayRecord.setTbUserInfo(tbUserInfo);
            payRecordMapper.insert(tbPayRecord);
            System.out.println(tbPayRecord);
            if (tbPayRecord.getId() != null) {
                resultMap.put("tbPayRecord", tbPayRecord);
                result.setResult(resultMap);
                result.setMessage("支付成功");
                //先获取购买的数量
                Integer buyNum = tbOrderGoods1.getBuyNum();
                //然后在书籍详情里减去已购买的数量
                int num = bookInventoryLevel-buyNum;
                //然后重新给书籍详情里的库存设值
                tbBookDetailed.setBookInventoryLevel(num);
                bookDetailedMapper.updateById(tbBookDetailed);
                System.out.println(tbBookDetailed);
                //根据售卖书籍的数量对应改变书籍单品的状态
                List<TbBookSingle> tbBookSingles = bookSingleMapper.selectList(
                        new QueryWrapper<TbBookSingle>()
                                .eq("book_detailed_code",tbBookDetailed.getCode())
                                .last("limit " + buyNum)
                );
                for(TbBookSingle  tbBookSingle:tbBookSingles){
                    tbBookSingle.setOnSellStatus(1);
                    bookSingleMapper.updateById(tbBookSingle);
                }
                System.out.println("------------tbBookSingles----------"+tbBookSingles);
                Double price = 0.0;

                tbOrderRecord.setOrderStatus(1);
                price = tbOrderRecord.getOrderPrice();
                orderRecordMapper.updateById(tbOrderRecord);

                tbPayRecord.setPayAmount(price);

                payRecordMapper.updateById(tbPayRecord);
                result.setResult(resultMap);
                return result;
            }
        }
        return result.setFail("支付失败");
    }


    /**
    　　* TODO  updateBookSingleStatus--修改单品书籍的状态
    　　* @Param [rfid]
    　　* @return com.bw.common.utils.ResponseResult
    　　* @author 钟乐
    　　* @date 2020/10/23 14:11
    　　*/
    @Override
    public ResponseResult updateBookSingleStatus(String rfids) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        String[] strings = rfids.split(",");

        //1、根据RFID查找单品书籍是否存在
        for(String rfid:strings) {
            TbBookSingle tbBookSingle = bookSingleMapper.selectById(rfid);
            if (tbBookSingle == null) {
                return result.setFail("该书籍单品不存在");
            }
            //2、判断该单品是否已经被售
            if (tbBookSingle.getOnSellStatus().equals(1)) {
                return result.setFail("该书籍单品已被售卖");
            }

            //3.修改该书籍单品的状态为已售卖
            tbBookSingle.setOnSellStatus(1);
            bookSingleMapper.updateById(tbBookSingle);
            resultMap.put("tbBookSingle", tbBookSingle);
        }
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult weChatPay() {
        return null;
    }

    @Override
    public ResponseResult appPayment() {
        return null;
    }


    @Resource
    private OrderRecordMapper orderRecordMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;

    @Resource
    private PayRecordMapper payRecordMapper;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private BookSingleMapper bookSingleMapper;

    @Resource
    private BookDetailedMapper bookDetailedMapper;


}
